//
//  LoginViewController.m
//  Cycling
//
//  Created by cjg.mini on 2023/3/3.
//

#import "LoginViewController.h"
#import "UserRequest.h"
#import "RegisterViewController.h"
#import "BaseNavigationController.h"
#import "BaseTabBarController.h"
#import "AppDelegate.h"
#import "GoogleSignInHelper.h"
#import "MineRequest.h"
#import <FBSDKLoginKit/FBSDKLoginKit.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import "ChooseAgeView.h"

@interface LoginViewController ()

@property (nonatomic, strong) UITextField *pwdF;
@property (nonatomic, strong) UITextField *accountF;
@property (nonatomic, strong) UIButton *loginBtn;
@property (nonatomic, strong) UIButton *Btn;
@property (nonatomic, strong) UIButton *registerBtn;
@property (nonatomic, strong) UIButton *forgetBtn;

@end

@implementation LoginViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];

}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configUI];
    
    // Do any additional setup after loading the view.
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
- (void)configUI {
    
    UIScrollView *bgView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    bgView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    [self.view addSubview:bgView];
    
    UIImageView *topImageView = [[UIImageView alloc] init];
    topImageView.image = [UIImage imageNamed:@"cycling"];
    [bgView addSubview:topImageView];
    [topImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(bgView);
        make.size.mas_equalTo(CGSizeMake(SCREEN_W, SCREEN_W));
    }];
    
    UILabel *titleL = [[UILabel alloc] init];
    titleL.text = @"Cycling";
    titleL.textColor = UIColor.whiteColor;
    titleL.textAlignment = NSTextAlignmentCenter;
    titleL.font = [UIFont systemFontOfSize:48];
    [bgView addSubview:titleL];
    [titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(bgView.mas_centerX);
        make.top.equalTo(topImageView.mas_top).offset(62);
    }];
    
    UILabel *contentL = [[UILabel alloc] init];
    contentL.text = @"Simple and environme";
    contentL.textColor = UIColor.whiteColor;
    contentL.textAlignment = NSTextAlignmentCenter;
    contentL.font = [UIFont systemFontOfSize:24];
    [bgView addSubview:contentL];
    [contentL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(bgView.mas_centerX);
        make.top.equalTo(titleL.mas_bottom).offset(10);
    }];
    
    UITextField *accountF = [[UITextField alloc] init];
    accountF.textColor = rgbHex(0xA6A6A6,1.0);
    accountF.placeholder = @"请输入账号";
    accountF.keyboardType = UIKeyboardTypeDefault;
    
    accountF.clearButtonMode = UITextFieldViewModeWhileEditing;
    accountF.borderStyle = UITextBorderStyleNone;
    [bgView addSubview:accountF];
    self.accountF = accountF;
    [accountF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bgView.mas_left).offset(31);
        make.top.equalTo(topImageView.mas_bottom).offset(20);
        make.right.equalTo(bgView.mas_right).offset(-31);
        make.height.offset(50);
    }];
    
    UIView *accountView = [[UIView alloc] init];
    accountView.backgroundColor = rgb(238, 238, 238);
    [bgView addSubview:accountView];
    [accountView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bgView.mas_left).offset(31);
        make.top.equalTo(accountF.mas_bottom).offset(0);
        make.right.equalTo(bgView.mas_right).offset(-31);
        make.height.offset(1);
    }];
    
    UITextField *pwdF = [[UITextField alloc] init];
    pwdF.placeholder = @"请输入密码";
    pwdF.textColor = rgbHex(0xA6A6A6,1.0);
    pwdF.borderStyle = UITextBorderStyleNone;
    
    pwdF.clearButtonMode = UITextFieldViewModeWhileEditing;
    pwdF.keyboardType = UIKeyboardTypeDefault;
    [bgView addSubview:pwdF];
    self.pwdF = pwdF;
    [pwdF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bgView.mas_left).offset(31);
        make.top.equalTo(accountF.mas_bottom).offset(10);
        make.right.equalTo(bgView.mas_right).offset(-104);
        make.height.offset(50);
    }];
    
    UIView *pwdView = [[UIView alloc] init];
    pwdView.backgroundColor = rgb(238, 238, 238);
    [bgView addSubview:pwdView];
    [pwdView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bgView.mas_left).offset(31);
        make.top.equalTo(pwdF.mas_bottom).offset(0);
        make.right.equalTo(bgView.mas_right).offset(-31);
        make.height.offset(1);
    }];
    
    UIButton *Btn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.pwdF.secureTextEntry = YES;
    [Btn setImage:[UIImage imageNamed:@"pwd_close"] forState:UIControlStateNormal];
    
    [Btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:Btn];
    self.Btn = Btn;
    [Btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(bgView.mas_right).offset(-26);
        make.centerY.equalTo(pwdF.mas_centerY);
        make.width.offset(46);
        make.height.offset(46);
    }];
    
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginBtn setBackgroundImage:[UIImage imageNamed:@"btn_login"] forState:UIControlStateNormal];
    loginBtn.titleLabel.font = [UIFont systemFontOfSize:24];
    [loginBtn addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:loginBtn];
    self.loginBtn = loginBtn;
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bgView.mas_left).offset(26);
        make.right.equalTo(bgView.mas_right).offset(-26);
        make.top.equalTo(pwdF.mas_bottom).offset(18);
        make.height.offset(62);
    }];
    
    UIButton *registerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [registerBtn setTitle:@"注册" forState:UIControlStateNormal];
    [registerBtn setTitleColor:rgb(10, 211, 159) forState:UIControlStateNormal];
    registerBtn.titleLabel.font = [UIFont systemFontOfSize:22];
    [registerBtn addTarget:self action:@selector(registerAccount) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:registerBtn];
    self.registerBtn = registerBtn;
    [registerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bgView.mas_left).offset(130);
        make.top.equalTo(loginBtn.mas_bottom).offset(2);
        make.width.offset(50);
        make.height.offset(40);
    }];
    
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = rgb(102, 102, 102);
    [bgView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.registerBtn.mas_right).offset(2);
        make.centerY.equalTo(self.registerBtn.mas_centerY);
        make.width.offset(4);
        make.height.offset(24);
    }];
    
    UIButton *forgetBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [forgetBtn setTitle:@"忘记密码" forState:UIControlStateNormal];
    [forgetBtn setTitleColor:rgb(102, 102, 102) forState:UIControlStateNormal];
    forgetBtn.titleLabel.font = [UIFont systemFontOfSize:22];
    [forgetBtn addTarget:self action:@selector(forgetPassword) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:forgetBtn];
    self.forgetBtn = forgetBtn;
    [forgetBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.registerBtn.mas_right).offset(4);
        make.centerY.equalTo(self.registerBtn.mas_centerY);
        make.width.offset(110);
        make.height.offset(40);
    }];
    
    UILabel *otherAccountL = [[UILabel alloc] init];
    otherAccountL.text = @"其它账户";
    otherAccountL.textColor = rgb(128, 128, 128);
    otherAccountL.textAlignment = NSTextAlignmentCenter;
    otherAccountL.font = [UIFont systemFontOfSize:22];
    [bgView addSubview:otherAccountL];
    [otherAccountL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(bgView);
        make.top.equalTo(self.forgetBtn.mas_bottom).offset(40);
    }];
    
    UIView *leftLineView = [[UIView alloc] init];
    leftLineView.backgroundColor = rgb(238, 238, 238);
    [bgView addSubview:leftLineView];
    [leftLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bgView.mas_left).offset(31);
        make.right.equalTo(otherAccountL.mas_left).offset(-33);
        make.centerY.equalTo(otherAccountL.mas_centerY);
        make.height.offset(1);
    }];
    
    UIView *rightLineView = [[UIView alloc] init];
    rightLineView.backgroundColor = rgb(238, 238, 238);
    [bgView addSubview:rightLineView];
    [rightLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(otherAccountL.mas_right).offset(33);
        make.centerY.equalTo(otherAccountL.mas_centerY);
        make.right.equalTo(bgView.mas_right).offset(-31);
        make.height.offset(1);
    }];
    
    UIButton *facebookBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [facebookBtn setImage:[UIImage imageNamed:@"Facebook"] forState:UIControlStateNormal];
    
    [facebookBtn addTarget:self action:@selector(facebookLogin) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:facebookBtn];
    [facebookBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(leftLineView.mas_bottom).offset(32);
        make.bottom.equalTo(bgView).offset(-SafeAreaBottomHeight-20);
        make.centerX.equalTo(bgView.mas_centerX).offset(-41);
        make.width.offset(44);
        make.height.offset(44);
    }];
    
    UIButton *googleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [googleBtn setImage:[UIImage imageNamed:@"goole"] forState:UIControlStateNormal];
    
    [googleBtn addTarget:self action:@selector(googleLogin) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:googleBtn];
    [googleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(leftLineView.mas_bottom).offset(32);
        make.bottom.equalTo(bgView).offset(-SafeAreaBottomHeight-20);
        make.centerX.equalTo(bgView.mas_centerX).offset(41);
        make.width.offset(44);
        make.height.offset(44);
    }];
    
}

- (void)btnClicked:(UIButton *)sender{
    sender.selected = !sender.selected;
    if (!sender.selected) {//隐藏密码
        self.pwdF.secureTextEntry = YES;
        [self.Btn setImage:[UIImage imageNamed:@"pwd_close"] forState:UIControlStateNormal];
    } else {//显示密码
        self.pwdF.secureTextEntry = NO;
        [self.Btn setImage:[UIImage imageNamed:@"pwd_open"] forState:UIControlStateNormal];
    }
}

- (void)login{
    if (IsStrEmpty(self.accountF.text)) {
        [HUDHelper showCustomAlertMessage:@"请输入账号"];
        return;
    }
    if (IsStrEmpty(self.pwdF.text)) {
        [HUDHelper showCustomAlertMessage:@"请输入密码"];
        return;
    }
        
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [UserRequest loginWithAccount:self.accountF.text password:[NSString stringWithFormat:@"%@",self.pwdF.text] result:^(UserModel *user) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (user) {
            [[NSUserDefaults standardUserDefaults] setValue:user.token forKey:@"Token"];
            [user updateUserInfo];
            [UserModel setLoginSatus:YES];
//            [MineRequest logcancellationResult:^(BOOL ret) {
//
//            }];
            appDelegate.window.rootViewController = [[BaseNavigationController alloc] initWithRootViewController:[[BaseTabBarController alloc] init]];
            [appDelegate.window makeKeyAndVisible];
        }
    }];
    
}

- (void)registerAccount {
    RegisterViewController *vc = [[RegisterViewController alloc] init];
    vc.type = ControllerTypeRegister;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)forgetPassword {
    RegisterViewController *vc = [[RegisterViewController alloc] init];
    vc.type = ControllerTypeForget;
    [self.navigationController pushViewController:vc animated:YES];
}

// facebook登陆
- (void)facebookLogin {
    FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];
    [loginManager logInWithPermissions:@[@"public_profile"] fromViewController:self handler:^(FBSDKLoginManagerLoginResult * _Nullable result, NSError * _Nullable error) {
         if (error) {
             NSLog(@"Process error");
          } else if (result.isCancelled) {
             NSLog(@"Cancelled");
          } else {
              NSString *facebookId =  result.token.userID;
              //用户的facebookId 传给后台 判断该用户是否绑定手机号，如果绑定了直接登录，如果没绑定跳绑定手机号页面
              [UserRequest thirdLoginWithPlatform:@"facebook" code:facebookId result:^(UserModel *user) {
                  if (user) {
                      [[NSUserDefaults standardUserDefaults] setValue:user.token forKey:@"Token"];
                      [user updateUserInfo];
                      [UserModel setLoginSatus:YES];
                      appDelegate.window.rootViewController = [[BaseNavigationController alloc] initWithRootViewController:[[BaseTabBarController alloc] init]];
                      [appDelegate.window makeKeyAndVisible];
                  }
              }];
          }
    }];
}

// goole登陆
- (void)googleLogin {
    [[GoogleSignInHelper shareInstance] signIn:^(BOOL ret, NSString * _Nonnull token) {
        if(ret){
            [UserRequest thirdLoginWithPlatform:@"google" code:token result:^(UserModel *user) {
                if (user) {
                    [[NSUserDefaults standardUserDefaults] setValue:user.token forKey:@"Token"];
                    [user updateUserInfo];
                    [UserModel setLoginSatus:YES];
                    appDelegate.window.rootViewController = [[BaseNavigationController alloc] initWithRootViewController:[[BaseTabBarController alloc] init]];
                    [appDelegate.window makeKeyAndVisible];
                }
            }];
        }else {
            
        }
    }];
}
@end
